package Meter::Users;

#===============================================================================
#     REVISION:  $Id: Users.pm 125 2011-07-25 11:10:52Z xdr.box@gmail.com $
#  DESCRIPTION:  Class::DBI wrapper for 'users' table
#===============================================================================

use strict;
use warnings;

use base qw(Meter::DBI);

use Readonly;
Readonly our $VERSION => qw($Revision: 125 $) [1];

use English qw( -no_match_vars );
use Regexp::Common qw(
    Email::Address
);

#use Smart::Comments;

## no critic (ProhibitEnumeratedClasses)

Readonly my $MIN_USERNAME_LENGTH => 3;
Readonly my $MAX_USERNAME_LENGTH => 32;
Readonly my $USERNAME_RE         => qr{
    \A
    [a-zA-Z][a-zA-Z0-9_-]{@{[$MIN_USERNAME_LENGTH-1]},@{[$MAX_USERNAME_LENGTH-1]}}
    \z
}xms;

Readonly my $MIN_PASSWORD_LENGTH => 6;
Readonly my $MAX_PASSWORD_LENGTH => 32;
Readonly my $PASSWORD_RE         => qr{
    \A
    [a-zA-Z0-9_-]{$MIN_PASSWORD_LENGTH,$MAX_PASSWORD_LENGTH}
    \z
}xms;

Readonly my $EMAIL_RE => qr/\A(?:$RE{Email}{Address})?\z/xms;

sub init_table {
    my $class = shift;

    __PACKAGE__->set_up_table('users');
    __PACKAGE__->has_many( appartments => 'Meter::Appartments' );
    __PACKAGE__->has_many( sessions    => 'Meter::Sessions' );

    __PACKAGE__->constrain_column( username => $USERNAME_RE );
    __PACKAGE__->constrain_column( password => $PASSWORD_RE );
    __PACKAGE__->constrain_column( email    => $EMAIL_RE );

    return;
}

sub appartment {
    my $self = shift;

    my @appartments = $self->appartments();
    if (@appartments) {
        return $appartments[0];    # first and the only
    }

    return;
}

1;
